package com.springcloudemo.ms.conf;


import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Properties;

/**
 * @author Yangdw
 * @date 2025-08-23
 * @description:
 */
public class NacosWritableDataSource<T> implements WritableDataSource<T> {


    private String dataId;
    private String group;
    private String serverAddr;
    private String namespace;

    private ConfigService configService ;


    public NacosWritableDataSource(String dataId,String group,String serverAddr
    ,String namespace) throws Exception {
        this.dataId = dataId;
        this.group = group;
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.NAMESPACE,namespace);
        properties.setProperty(PropertyKeyConst.SERVER_ADDR,serverAddr);


        this.configService = NacosFactory.createConfigService(properties);
    }

    @Override
    public void write(T t) throws Exception {
        configService.publishConfig(this.dataId,this.group, JSON.toJSONString(t));
    }

    @Override
    public void close() throws Exception {

    }
}
